package com.saicmotor.keeplive;

import android.app.ActivityManager;
import android.app.Notification;
import android.app.Service;
import android.app.job.JobInfo;
import android.app.job.JobParameters;
import android.app.job.JobScheduler;
import android.app.job.JobService;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;

import androidx.annotation.RequiresApi;

import com.fanjun.keeplive.KeepLive;
import com.fanjun.keeplive.config.NotificationUtils;
import com.fanjun.keeplive.receiver.NotificationClickReceiver;

/**
 * @Author xinxinzhang
 * @Date 2022/08/19
 **/
@SuppressWarnings(value = {"unchecked", "deprecation"})
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
public class JobHandlerService extends JobService {

    private JobScheduler jobScheduler;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        int id = startId;
        startService(this);
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP) {
            jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
            JobInfo.Builder builder =
                    new JobInfo.Builder(id++,
                            new ComponentName(getPackageName(), JobHandlerService.class.getName()));
            if (Build.VERSION.SDK_INT == 24) {
                builder.setMinimumLatency(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS);
                builder.setOverrideDeadline(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS);
                builder.setMinimumLatency(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS);
                builder.setBackoffCriteria(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS, JobInfo.BACKOFF_POLICY_LINEAR);
            } else {
                builder.setPeriodic(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS);
            }
            builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
            builder.setRequiresCharging(true);
            jobScheduler.schedule(builder.build());
        }

        return Service.START_STICKY;
    }

    private void startService(Context context) {
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O) {
            if (KeepLive.foregroundNotification != null) {
                Intent intent = new Intent(getApplicationContext(), NotificationClickReceiver.class);
                intent.setAction(NotificationClickReceiver.CLICK_NOTIFICATION);
                Notification notification = NotificationUtils.createNotification(this,
                        KeepLive.foregroundNotification.getTitle(),
                        KeepLive.foregroundNotification.getDescription(),
                        KeepLive.foregroundNotification.getIconRes(),
                        intent);
                startForeground(13691, notification);
            }
        }

        // 启动本地服务
        Intent local = new Intent(context, LocalService.class);
        // 启动守护线程
        Intent remote = new Intent(context, RemoteService.class);
        startService(local);
        startService(remote);

    }

    @Override
    public boolean onStartJob(JobParameters jobParameters) {
        if (!isServiceRunning(getApplicationContext(), LocalService.class.getName())) {
            startService(this);
        }
        return false;
    }

    @Override
    public boolean onStopJob(JobParameters jobParameters) {
        if (!isServiceRunning(getApplicationContext(), LocalService.class.getName())) {
            startService(this);
        }
        return false;
    }

    private boolean isServiceRunning(Context context, String className) {
        boolean isRunning = false;
        ActivityManager activityManager =
                (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo info :
                activityManager.getRunningServices((Integer.MAX_VALUE))) {
            if (className.equals(info.getClass().getName())) {
                isRunning = true;
            }
        }
        return isRunning;
    }
}
